var map = new BMap.Map('left_map', {enableMapClick:false}),  // 创建Map实例
    cityID, //城市id
    cityName; //城市名
map.enableScrollWheelZoom();                                   //启动鼠标滚轮操作
map.disableDoubleClickZoom();                                   //禁用双击放大
map.addControl(new BMap.NavigationControl());                  //添加默认缩放平移控件

function get_city() {

    cityID = $('#city').val();
    cityName = $('#city').find('option:selected').text();

}
get_city();


//移动地图中心点
function center_and_zoom() {
    map.centerAndZoom(cityName, 13);
}
center_and_zoom();


/**
 * 画图初始化
 */
function draw_init() {

    var color = $('#color').val();

    var styleOptions = {
        strokeColor: color,    //边线颜色。
        fillColor: color,      //填充颜色。当参数为空时，圆形将没有填充效果。
        strokeWeight: 1,       //边线的宽度，以像素为单位。
        strokeOpacity: 0.8,	   //边线透明度，取值范围0 - 1。
        fillOpacity: 0.6,      //填充的透明度，取值范围0 - 1。
        strokeStyle: 'solid' //边线的样式，solid或dashed。
    }

    //实例化鼠标绘制工具
    drawingManager = new BMapLib.DrawingManager(map, {
        isOpen: false, //是否开启绘制模式
        enableDrawingTool: true, //是否显示工具栏
        drawingToolOptions: {
            anchor: BMAP_ANCHOR_TOP_RIGHT, //位置
            offset: new BMap.Size(5, 5), //偏离值
            scale: 0.8 //工具栏缩放比例
        },
        polygonOptions: styleOptions //多边形的样式
    });

    $('.BMapLib_marker').hide();
    $('.BMapLib_circle').hide();
    $('.BMapLib_polyline').hide();
    $('.BMapLib_rectangle').hide();

    //完成绘制多边形完成后，派发的事件接口
    drawingManager.addEventListener('polygoncomplete', function(e) {

        mapArea.add.obj = e;

        E.popup.open({
            id: 'pop',             //获取id为'pop'元素内的HTML
            title: '区域详情',      //弹出层标题
            css: 'width: 700px;', //设置弹出层样式
            btnName: '保存',      //执行“确定”操作的按钮名称
            btnCall: 'mapArea.add.check();'  //点击确定后执行的方法
        }, 'mapArea.add.cancel');

    });

}
draw_init();


var mapArea = {

    areaBox: {},

    checkedBox: {},

    pathOverlay: function( area_obj ) {

        //设置多边形样式
        var polygon = new BMap.Polygon();
        polygon.setPath( area_obj.path );
        polygon.setStrokeColor(area_obj.colour);
        polygon.setFillColor(area_obj.colour);
        polygon.setStrokeOpacity(0.8);
        polygon.setFillOpacity(0.6);
        polygon.setStrokeWeight(1);
        polygon.setStrokeStyle('solid');
        map.addOverlay(polygon);

        //鼠标点击修改
        polygon.addEventListener('click', function() {

            if (!polygon.edit_flg || polygon.edit_flg == 0) {
                polygon.enableEditing();
                $('#color').val(area_obj.colour).css('color', area_obj.colour);
                polygon.edit_flg = 1;
            } else {
                polygon.disableEditing();
                polygon.edit_flg = 0;
            }

        });

        //双击修改成功
        polygon.addEventListener('dblclick', function() {

            if (!polygon.edit_flg || polygon.edit_flg == 0) {
                return false;
            }

            polygon.disableEditing();

            mapArea.add.obj = polygon;

            E.popup.open({
                id: 'pop',             //获取id为'pop'元素内的HTML
                title: '区域详情',      //弹出层标题
                css: 'width: 700px;', //设置弹出层样式
                btnName: '保存',      //执行“确定”操作的按钮名称
                btnCall: 'mapArea.add.check();'  //点击确定后执行的方法
            }, 'mapArea.add.cancel');

            $('#areaID').val(area_obj.areaID);
            $('#areaName').val(area_obj.areaName);
            $('#areaCode').val(area_obj.areaCode);
            $('#type').val(area_obj.type);

            if(area_obj.brand)
            {
                $("input[name='brand']").each(function(){
                    var val = parseInt( $(this).val());

                    if($.inArray(val,area_obj.brand)>=0)
                    {
                        $(this).attr('checked','checked');
                    }
                    else
                    {
                        $(this).removeAttr('checked');
                    }


                });
            }

        });

    },

    search: {

        execute: function() {

            $('#right_list').html( '正在加载...' );
            E.ajax_get({
                url:'/invokingAjax-backend/system/mapAreaZoning.ajax?operFlg=1',
                data: {
                    cityID: cityID
                },
                call: 'mapArea.search.result'
            });

        },

        result: function( o ) {

            map.clearOverlays();

            if (o.code == 200) {

                var html = '<table class="table table-bordered">';
                html += '<tbody>';

                $.each(o.data, function(k, v) {

                    if (k == 1) {
                        var typeName = '配送站';
                    } else if ( k == 2 ) {
                        var typeName = '运费';
                    } else {
                        return false;
                    }

                    html += '<tr>';
                    html += '<td>';
                    html += typeName;
                    html += '</td>';
                    html += '</tr>';

                    $.each(v, function(i, j) {

                        html += '<tr>';
                        html += '<td class="map_area_line">';
                        if (mapArea.checkedBox[j.areaID]) {
                            html += '<input type="checkbox" class="square-radio" id="map_area_line_' + j.areaID + '" name="map_area_line" value="' + j.areaID + '" checked />&nbsp;&nbsp;';
                        } else {
                            html += '<input type="checkbox" class="square-radio" id="map_area_line_' + j.areaID + '" name="map_area_line" value="' + j.areaID + '" />&nbsp;&nbsp;';
                        }

                        html += '<label for="map_area_type_' + j.areaID + '">' + j.areaName + '</label>';
                        html += '&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript: void(0);" onclick="mapArea.del(' + j.areaID + ');">删除</a>';
                        html += '</td>';
                        html += '</tr>';


                        var points_array = new Array();

                        if(j.path)
                        {
                            $.each(j.path, function(x, y) {

                                points_array[x] = {
                                    //mod by allen.qiang 20150422 坐标数据类似改为 浮点数 --start
                                    lat: parseFloat(y.latitude),
                                    lng: parseFloat(y.longitude)
                                    //mod by allen.qiang 20150422 坐标数据类似改为 浮点数 --end
                                };

                            });
                        }

                        var brand_array = new Array();
                        if(j.brand)
                        {
                            $.each(j.brand,function(x , y){
                                brand_array[x] = y.brandID;
                            });
                        }

                        mapArea.areaBox[j.areaID] = {
                            path: points_array,
                            brand: brand_array,
                            colour: j.colour,
                            areaID: j.areaID,
                            areaName: j.areaName,
                            type: j.type,
                            areaCode: j.areaCode
                        };

                        if (mapArea.checkedBox[j.areaID]) {
                            mapArea.pathOverlay( mapArea.areaBox[j.areaID] );
                        }


                    });

                });

                html += '</tbody>';
                html += '</table>';
                $('#right_list').html( html );

                $('.square-radio').iCheck({
                    checkboxClass: 'icheckbox_square-blue',
                    radioClass: 'iradio_square-blue',
                    increaseArea: '20%' // optional
                });

                draw_init();

            } else {

                $('#right_list').html( o.message );

            }

        }

    },

    add: {

        check: function() {

            this.dt = E.getFormValues('areaForm');

            var error_msg = '';
            if ( this.dt.areaName == '' ) {
                error_msg += '区域名称不能为空<br />';
            }
            if ( this.dt.areaCode == '' ) {
                error_msg += '区域编码不能为空<br />';
            }
            if ( this.dt.type == '' ) {
                error_msg += '请选择类型<br />';
            }

            if (error_msg != '') {
                E.alert(error_msg);
            } else {
                E.confirm('您确认保存该区域名称吗?', 'mapArea.add.execute');
            }

        },

        execute: function() {

            E.loadding.open('正在保存，请稍候...');

            this.dt.cityID = cityID;
            this.dt.color = $('#color').val();
            this.dt.path = this.obj.getPath();

            E.ajax_post({
                url:'/invokingAjax-backend/system/mapAreaZoning.ajax?operFlg=100&act=edit', //传递到后台
                data: this.dt,
                call:'mapArea.add.result'
            });

        },

        result: function( o ) {

            E.loadding.close();

            if ( o.code == 200 ) {
                E.popup.close(1);
                E.alert( o.message, 2);
                mapArea.checkedBox[o.data.areaID] = 1;
                mapArea.search.execute();
            } else {
                E.alert(o.message,1);
            }

        },

        cancel: function() {
            this.obj.remove();
            draw_init();
        }

    },

    del: function( areaID ) {

        E.confirm('您确认要删除改地图区域吗？', function() {

            E.loadding.open('正在删除，请稍候...');
            E.ajax_get({
                url: '/invokingAjax-backend/system/mapAreaZoning.ajax?operFlg=100&act=del', //传递到后台
                data: {
                    areaID: areaID
                },
                call: function( o ) {
                    E.loadding.close();
                    if (o.code == 200) {
                        mapArea.search.execute();
                    } else {
                        E.alert(o.message);
                    }
                }
            });

        });

    }

};
mapArea.search.execute();


$(window).ready(function() {

    $('#city').on('change', function() {
        get_city();
        center_and_zoom();
        mapArea.search.execute();
    });

    $(document).on('ifChecked', 'input[name=map_area_line]', function() {

        var areaID = $(this).val();

        var area_obj = mapArea.areaBox[areaID];

        mapArea.checkedBox[areaID] = 1;
        mapArea.pathOverlay( area_obj );

    });

    $(document).on('ifUnchecked', 'input[name=map_area_line]', function() {

        map.clearOverlays();

        var areaID = $(this).val();

        delete mapArea.checkedBox[areaID];

        $.each(mapArea.checkedBox, function(k ,v) {

            var area_obj = mapArea.areaBox[k];

            mapArea.pathOverlay( area_obj );

        });

        draw_init();

    });

    $('#color').colorpicker({
        fillcolor:true,
        success:function() {
            draw_init();
        }, //回调函数
        reset:function() {
            draw_init();
        }
    });

});
